function [head,data] = txtReadData(filena)
%txtReadData - header and data extration from a txt file
%
%       [HEAD,DATA] = txtReadData(FILENA)
% 
% This function provides the header HEAD (as a char array, if the header
% exists; if the header does not exist, it is HEAD = []) and the numerical
% data array DATA from the file FILENA.
% If FILENA is undefined or empty, the filename can be managed by means of
% a dialog box.

% G. Teza, 2022 (with an ancillary function derived by Walter Roberson's
% function linecount)

if nargin < 1 || isempty(filena)
    [fily1,pathy1] = uigetfile(...
        {'*.txt','(*.txt)';'*.dat','(*.dat)';'*.asc','(*.asc)';'*.mom','(*.mom)'},...
        'ASCII FILE');
    if isnumeric(fily1) || isnumeric(pathy1)
        filena = []; 
    else
        filena = fullfile(pathy1,fily1);
    end
end
if isempty(filena)
    head = [];
    data = [];
    return
end

[ntot,nhead] = linecount(filena);   % ancillary function, see below

% head extraction:
if nhead > 0
    fid = fopen(filena,'r');
    head = cell(nhead,1);
    for k = 1:nhead
        headk = fgetl(fid);
        head(k) = {headk};
    end
    fclose(fid);
else
    head = [];
end

% data extraction (the problem of header rows having a numerical element
% and # elements equal to # data columns must be solved):
data = readmatrix(filena,"FileType",'text',"NumHeaderLines",nhead);

%% Ancillary functions:

function [ntot,nhead] = linecount(filename)
% ntot : file lines
% nhead: head lines
% Modified from linecount by Walter Roberson
% (https://it.mathworks.com/matlabcentral/profile/authors/434782)
[fid, msg] = fopen(filename);
if fid < 0
    error('Failed to open file "%s" because "%s"', filename, msg);
end
ntot = 0;
nhead = 0;
flaghead = true;
while true
    % test 'existing valid row':
    t = fgetl(fid);
    if ~ischar(t)
        break
    else
        ntot = ntot+1;
    end
    % headtest (with 'flaghead', the 'headtest' is non performed if
    % unnecessary)
    if flaghead     
        t = str2num(t); %#ok<ST2NM> (str2double is invalid in this case)
        if isempty(t)
            nhead = nhead+1;
        else
            flaghead = false;
        end
    end
 end
 fclose(fid);